<template>
  <div class="app-container">
    <el-row style="margin-bottom:10px">
      <el-col :span="4">
        <el-input v-model="search.keyword" placeholder="Keywords" style="width:95%" />
      </el-col>
      <el-button type="primary" @click="getRoles">Search</el-button>
      <el-button type="primary" @click="handleAddRole">Add</el-button>
    </el-row>
    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border empty-text="Can't find record in table">
      <el-table-column align="center" prop="id" label="ID" width="70">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" label="Title" width="400">
        <template slot-scope="scope">{{ scope.row.title }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Wi Type" width="90">
        <template slot-scope="scope">{{ scope.row.wi_type_name }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Clients">
        <template slot-scope="scope">{{ scope.row.hotel_names }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Enabled" width="90">
        <template slot-scope="scope"><el-checkbox :value="scope.row.status===1" /></template>
      </el-table-column>
      <el-table-column align="center" label="Action" width="80">
        <template slot-scope="scope">
          <el-col :span="12">
            <el-link style="font-size:18px;" class="el-icon-edit icon-class" @click="handleEdit(scope)" />
          </el-col>
          <el-col :span="12">
            <el-link style="font-size:18px;" class="el-icon-delete icon-class" @click="handleDelete(scope)" />
          </el-col>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialogVisible"
      width="900px"
      :title="dialogType === 'edit' ? 'Edit Work Instruction' : 'New Work Instruction'"
    >
      <div style="margin:0 30px">
        <el-form ref="connectForm" :model="role" label-width="150px" :rules="rules" label-position="left">
          <el-form-item label="Title" prop="title">
            <el-input v-model="role.title" placeholder="Title" />
          </el-form-item>
          <el-form-item label="Wi Type" prop="wi_type">
            <el-select v-model="role.wi_type" placeholder="Please Choose" no-data-text="Can't find record">
              <el-option
                v-for="item in wi_types"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Clients">
            <el-select v-model="wi_hotelids" multiple placeholder="Please Choose" no-data-text="Can't find record" style="width:100%">
              <el-option
                v-for="item in wi_hotellist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Enabled">
            <el-checkbox v-model="chadex" style />
          </el-form-item>
        </el-form>
        <hr>
        <el-row :gutter="24" style="height: 30px;">
          <el-col :span="7">Step</el-col>
          <el-col :span="9">Title</el-col>
          <el-col :span="4">Template</el-col>
          <!-- <el-col :span="3">Content</el-col> -->
          <el-col style="padding-left: 20px" :span="4">
            <el-checkbox v-model="check_all" @change="handleCheckAllChange">Require</el-checkbox>
          </el-col>
        </el-row>
        <section>
          <my-test
            v-for="(item, index) in people"
            ref="mytestForm"
            :key="index"
            :index="index"
            :item-c="item"
            :flag="item.flag"
            :template-list="Templatelist"
            @deleteIndex="del"
          />
          <el-button style="margin-top:20px;" @click="add()">Add</el-button>

          <!-- <el-table
            :data="hotellist"
            height="250"
            style="width: 100%;margin-top:30px;margin-bottom:20px"
            border
          >
            <el-table-column align="center" prop="id" label="ID" width="120">
              <template slot-scope="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <el-table-column align="center" label="Hotel Name" width="140">
              <template slot-scope="scope">{{ scope.row.hotel_name }}</template>
            </el-table-column>
            <el-table-column align="header-center" label="Address">
              <template slot-scope="scope">{{ scope.row.address }}</template>
            </el-table-column>
            <el-table-column align="header-center" label="Wi Type Name">
              <template slot-scope="scope">{{ scope.row.wi_type_name }}</template>
            </el-table-column>
            <el-table-column align="header-center" label="En Flag">
              <template slot-scope="scope">
                <el-checkbox :value="scope.row.en_flag===1" />
              </template>
            </el-table-column>
            <el-table-column align="header-center" label="Create Time">
              <template slot-scope="scope">{{ scope.row.create_time }}</template>
            </el-table-column>
            <el-table-column align="header-center" label="Update Time">
              <template slot-scope="scope">{{ scope.row.update_time }}</template>
            </el-table-column>
          </el-table> -->
        </section>
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmRole">Confirm</el-button>
        </div>
      </div>
    </el-dialog>
    <el-pagination
      style="margin-top:10px;float:right"
      background
      layout="prev,pager,next"
      :total="totalpage"
      :current-page="search.page"
      :page-size="search.per_page"
      @current-change="handleIndexChange"
    />
  </div>
</template>

<script>
import { baseAPI } from '@/utils/request'
import MyTest from './module.vue'
import {
  getjobinfo,
  deletejob,
  savejob,
  getdetail,
  getdictionary,
  deletewistep
} from '@/api/Instruction/joblist/index'

export default {
  components: {
    MyTest
  },
  data() {
    return {
      Templatelist: [],
      TemplateDefault: '',
      people: [
        {
          id: '',
          template_id: 0,
          step: '',
          title: '',
          is_require: '',
          is_chadex: false,
          flag: true
        }
      ],
      people2: [
        {
          id: '',
          title: '',
          template_id: 0,
          step: '',
          is_require: '',
          flag: true
        }
      ],
      role: {
        id: '',
        title: '',
        wi_type: '',
        status: '',
        wi_hotel: [],
        wi_step: [
          {
            id: '',
            wi_id: '',
            template_id: '',
            step: '',
            content: '',
            is_require: '',
            flag: true
          }
        ]
      },
      status2: '',
      search: {
        keyword: '',
        page: 1,
        per_page: 10
      },
      wi_types: [
        {
          value: '',
          name: ''
        }
      ],
      isIndeterminate: true,
      check_all: false,
      chadex: true,
      hotellist: [],
      wi_hotellist: [],
      wi_hotelids: [],
      totalpage: 0,
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        title: [{ required: true, message: 'Please enter a title', trigger: 'blur'
        }],
        wi_type: [{ required: true, message: 'Please Choose Wi Type', trigger: 'change'
        }]
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  watch: {
    dialogVisible(newValue, oldValue) {
      this.role = {
        id: '',
        title: '',
        wi_type: '',
        status: '',
        wi_hotel: [],
        wi_step: [
          {
            id: '',
            wi_id: '',
            template_id: '',
            step: '',
            content: '',
            is_require: '',
            flag: true
          }
        ]
      }
      if (this.$refs['connectForm']) this.$refs['connectForm'].clearValidate()

      if (!newValue) {
        this.Templatelist = []
        this.people = [
          {
            id: '',
            template_id: 0,
            step: '',
            title: '',
            is_require: '',
            is_chadex: false,
            flag: true
          }
        ]
      }
    }
  },
  created() {
    this.getRoutes()
    this.getRoles()
  },
  methods: {
    handleCheckAllChange(val) {
      this.people.forEach(person => {
        person.is_chadex = val
      })
    },
    async getTemplatelist() {
      this.Templatelist = await getdictionary({ dict_type: 'wi_template' })
      if (this.Templatelist.length > 0) {
        this.TemplateDefault = this.Templatelist[0].value
      }
    },
    add() {
      this.people.push({
        id: '',
        template_id: this.TemplateDefault,
        step: '',
        title: '',
        is_require: '',
        is_chadex: true,
        flag: true
      })
      for (var i = 0; i < this.people.length; i++) {
        this.people[i].step = i + 1
      }
    },
    async del(val) {
      if (this.people[val].id !== '' && this.people[val].id !== null) {
        await deletewistep({ id: this.people[val].id })
      }
      this.people.splice(val, 1)
      for (var i = 0; i < this.people.length; i++) {
        this.people[i].step = i + 1
      }
    },
    handleIndexChange(index) {
      this.search.page = index
      this.getRoles()
    },
    async gethotellist() {
      this.wi_hotellist = await getdictionary({ dict_type: 'hotel' })
    },
    async getwitypeinfo() {
      this.wi_types = await getdictionary({ dict_type: 'auth_wi_type' })
      this.role.wi_type = 1
    },
    async getRoutes() {
      const res = await baseAPI.get('user/role/routes')
      this.serviceRoutes = res
      this.routes = res
    },
    async getRoles() {
      const res = await getjobinfo(this.search)
      this.rolesList = res.data
      this.totalpage = res.total
      this.search.per_page = parseInt(res.per_page)
      this.search.page = parseInt(res.current_page)
    },
    handleAddRole() {
      this.getTemplatelist()
      this.getwitypeinfo()
      this.wi_hotelids = []
      this.people.splice(this.people)
      this.gethotellist()
      this.hotellist.splice(this.hotellist)
      this.people.push({
        template_id: this.TemplateDefault,
        step: '1',
        title: '',
        is_require: '',
        is_chadex: true,
        flag: true
      })
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    async handleEdit(scope) {
      this.getwitypeinfo()
      this.people.splice(this.people)
      this.gethotellist()
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      const res = await getdetail({ id: scope.row.id })
      this.wi_hotelids = res.wi_hotel
      this.role.id = res.id
      this.role.status = res.status
      this.role.title = res.title
      this.role.wi_type = res.wi_type
      this.people = res.wi_step
      this.people.flag = true
      this.hotellist = res.hotels
      this.people.forEach(element => {
        if (element.is_require === 1) {
          element.is_chadex = true
        } else {
          element.is_require = false
        }
      })
      if (this.role.status === 1) {
        this.chadex = true
      } else {
        this.chadex = false
      }
    },
    handleDelete({ $index, row }) {
      this.$confirm('Confirm to remove the role?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
        .then(async() => {
          await deletejob({ id: row.id })
          this.rolesList.splice($index, 1)
          this.getRoles()
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    async confirmRole() {
      this.$refs.connectForm.validate(async valid => {
        if (valid) {
          this.people2.splice(this.people2)
          this.people.forEach(element => {
            if (element.is_chadex) {
              element.is_require = 1
            } else {
              element.is_require = 0
            }
            this.people2.push({
              id: element.id,
              title: element.title,
              template_id: element.template_id,
              step: element.step,
              is_require: element.is_require
            })
          })
          this.role.wi_step = this.people2
          this.role.wi_hotel = this.wi_hotelids
          if (this.chadex) {
            this.status2 = 1
          } else {
            this.status2 = 0
          }
          this.role.status = this.status2
          await savejob(this.role)
          this.dialogVisible = false
          this.getRoles()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
